import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter_book/api/dou_ban_api.dart';
import 'package:flutter_book/config/application.dart';
import 'package:flutter_book/constant/color.dart';
import 'package:flutter_book/constant/style.dart';
import 'package:flutter_book/data/database/collect_book_helper.dart';
import 'package:flutter_book/data/model/book_model.dart';
import 'package:flutter_book/data/model/video_model.dart';
import 'package:flutter_book/route/router.dart';
import 'package:flutter_book/widget/common/Image_widget.dart';
import 'package:flutter_book/widget/common/app_icon_button.dart';
import 'package:flutter_book/widget/common/common_widget.dart';
import 'package:flutter_book/util/extensions/string_extensions.dart';
import 'package:flutter_book/util/extensions/widget_extensions.dart';
import 'package:flutter_book/widget/slider/complicated_image_slider.dart';
import 'package:get/get.dart';

class TabHomePage extends StatefulWidget {

  final Function(Function(bool isPlay)) isPlayListener;

  TabHomePage(this.isPlayListener);

  @override
  _TabHomePageState createState() => _TabHomePageState();
}

class _TabHomePageState extends State<TabHomePage> with AutomaticKeepAliveClientMixin{

  @override
  bool get wantKeepAlive => true;

  late CollectBookController _bookController;

  @override
  void initState() {
    super.initState();
    _bookController = CollectBookController();
    Application.collectBookController = _bookController;
    _bookController.init();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      color: AppColor.white,
      child: Column(
        children: [
          _getTopSearchBar(),
          SizedBox(height: 12),
          // _getVideoBanner(),
          Expanded(child: _getGridViewBook()),
        ],
      ),
    );
  }

  //顶部搜索
  Widget _getTopSearchBar(){
    return Container(
      padding: EdgeInsets.only(right: 16),
      child: Row(
        children: [
          _getSearchBox(),
          AppIconButton(
            iconSize: 27,
            icon: Icons.history_outlined,
            iconColor: AppColor.black.withOpacity(0.8),
            buttonHeight: 32,
            buttonWidth: 32,
          ),
          AppIconButton(
            iconSize: 27,
            icon: Icons.history_outlined,
            iconColor: AppColor.black.withOpacity(0.8),
            buttonHeight: 32,
            buttonWidth: 32,
          ),
        ],
      ),
    );
  }

  Widget _getSearchBox(){
    return Expanded(child: SizedBox(
      child: Container(
        height: 32,
        margin: EdgeInsets.symmetric(horizontal: 16),
        padding: EdgeInsets.only(left: 10),
        decoration: BoxDecoration(
          color: AppColor.bgWhite,
          borderRadius: BorderRadius.circular(16),
        ),
        alignment: Alignment.centerLeft,
        child: AppIconButton(
          iconSize: 20,
          icon: Icons.search_outlined,
          iconColor:AppColor.black.withOpacity(0.2),
        ),
      ).onTap((){
        "点击了搜索按钮".print;
        AppRouter.toSearchBookPage();
      }),
    ));
  }


  Widget _getVideoBanner(){
    return FutureBuilder(
        future: DouBanApi.init().getDouBanVideoListNumber(number: 5),
        builder: (BuildContext context, AsyncSnapshot<List<VideoModel>?> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              return Container(child: Text(snapshot.error.toString()));
            }
            if (snapshot.data == null || snapshot.data!.length < 1) {
              return Container(child: Text("暂无数据"));
            }
            return Container(
                child: ComplicatedImageSlider(snapshot.data, _onClickBannerListener, widget.isPlayListener));
          }
          return Container(child: Text("正在加载"));
        }
    );
  }


  Widget _getGridViewBook() {
    return RefreshIndicator(
      onRefresh: () async {
        _bookController.init();
      },
      child: Obx(() {
        return GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            childAspectRatio: 0.7,
          ),
          itemCount: _bookController.collectBookList.length,
          itemBuilder: (context, index) {
            return _getBookItem(_bookController.collectBookList[index]);
          },
        );
      }
      ),
    );
  }

  Widget _getBookItem(BookModel bookModel) {
    return Container(
      color: AppColor.transparent,
      child: UnconstrainedBox(
        alignment: Alignment.topCenter,
        child: Column(
          children: [
            Container(
              height: 129,
              width: 85,
              child: ImageWidget.network(
                  bookModel.cover ?? "",
                  errorWidget: ImageWidget.asset("assets/png/login_bg.png")
              ),
            ),
            SizedBox(height: 6),
            SizedBox(
              width: 85,
              child: Text(bookModel.title ?? "",
                style: AppStyle.textMedium14,
                overflow: TextOverflow.ellipsis,
                textAlign: TextAlign.center,
                maxLines: 1,
              ),
            ),
          ],
        ),
      ),
    ).onTap(() {
      if (bookModel.id != null) {
        AppRouter.toBookPage(bookModel);
      } else {
        "获取数据信息失败".toast;
      }
    });
  }


  //banner位的点击事件
  _onClickBannerListener(VideoModel model) {
    "model:${model.toJson().toString()}".print;
  }


}


class CollectBookController extends GetxController {
  var collectBookList = <BookModel>[].obs;

  init() async {
    collectBookList.value = await CollectBookHelper.init().queryAll();
  }

  removeItem(BookModel model) {
    for (var dto in collectBookList) {
      if (dto.id == model.id) {
        collectBookList.remove(dto);
        return;
      }
    }
  }

  addItem(BookModel model) {
    collectBookList.insert(0, model);
  }
}
